/*
 * @Author: luojianfeng
 * @Date: 2023-07-17 09:46:48
 * @LastEditTime: 2025-01-14 16:39:36
 * @LastEditors: luojianfeng
 * @Description:公共函数
 */
//加密字符串
/**
 * @description 字符串变星号
 * @param {string} str - 需要传入的字符串
 * @param {number} len1 - 保留前几位不变
 * @param {number} len2 - 保留后面几位不变星号
 * @export
 */
export const changeToStar = (str: string, len1: number, len2 = 0): string => {
  const strLen = str.length
  let stars = ''
  for (let i = 0; i < strLen - len1 - len2; i++) {
    stars += '*'
  }
  str = str.substring(0, len1) + stars + str.substring(strLen - len2)
  return str
}

/**
 * await 包装函数
 * @param { Promise } promise
 * @param { Object= } errorExt - Additional Information you can pass to the err object
 * @return { Promise }
 */
export function awaitTo<T, U = Error>(
  awaited: T,
  errorExt?: object
): Promise<[U, undefined] | [null, T]> {
  const promise = Promise.resolve(awaited) // 非Promise则转为Promise
  return promise
    .then<[null, T]>((data: T) => [null, data])
    .catch<[U, undefined]>((err: U) => {
      if (errorExt) {
        const parsedError = Object.assign({}, err, errorExt)
        return [parsedError, undefined]
      }

      return [err, undefined]
    })
}

/**
 * 递归查找
 * @param list
 * @param fn
 * @param childName
 * @returns
 */
export const deepFind = (
  list: any[],
  fn: (e: any) => boolean,
  childName = 'children'
) => {
  const res: any[] = []
  const traverse = function (node: any[]) {
    node.forEach((item: any) => {
      if (fn(item)) {
        res.push(item)
      } else {
        item[childName] && traverse(item[childName])
      }
    })
  }
  traverse(list)
  return res
}
//错误提示
export const errorHandling = <T>(fn: (...rest: T[]) => void, args?: T[]) => {
  let result
  try {
    result = args ? fn(...args) : fn()
  } catch (error) {
    console.error(error)
  }
  return result
}
//获取文件后缀
export const getFileExtension = (filename: string): string => {
  if (!filename) return ''

  // 使用正则表达式匹配文件后缀
  const match = filename.match(/\.([^.]+)$/)

  // 如果匹配成功，返回后缀名，否则返回空字符串
  return match ? match[1] : ''
}
